﻿using System;

using Adaptive.Agrona;

using Unity.Connections;
using Unity.Credentials;

namespace Unity.Commons.Client.Offline
{
    public class OfflineProducer : IUnityProducer
    {
        private readonly IOfflineHandler _offlineHandler;
        private bool _disposed;
        private int _batchingCounter = 0;

        public OfflineProducer(IOfflineHandler offlineHandler)
        {
            _offlineHandler = offlineHandler;
        }

        public bool Produce(IDirectBuffer buffer, int offset, int length)
        {
            _offlineHandler.onAction(buffer, offset, length);
            return true;
        }

        public bool AddToBatching(IDirectBuffer buffer, int offset, int length)
        {
            _batchingCounter++;
            return Produce(buffer, offset, length);
        }

        public int CompleteBatching()
        {
            int batchingCounter = _batchingCounter;
            _batchingCounter = 0;
            return batchingCounter;
        }

        public bool Connect(IUnityCredentials credentials)
        {
            return true;
        }

        public void Close()
        {
            // Method intentionally left empty.
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                Close();    
            }

            _disposed = true;
        }
    }
}
